import React, { useMemo } from "react";
import { Form, Input, Button } from "antd-mobile";
import request from "../../api/request";
import { useCountDown } from "../../utils/countDown";
import { useNavigate } from "react-router-dom";
import { debounce } from "lodash";
function Index() {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { count, CountDown } = useCountDown(10);
  const maxnum = 10;

  const onFinish = debounce(async (values) => {
    const res = await request.post("/api/login/tel", values);
    console.log(res);
    if (res.code === 200) {
      // 存储token
      localStorage.setItem("token", res.token);
    }
  }, 1000);

  const codeCon = useMemo(() => {
    if (count === maxnum) return "获取验证码";
    return `${count}s后重新获取`;
  }, [count]);

  const hanYan = async () => {
    form.validateFields(["tel"]).then(async ({ tel }) => {
      CountDown();
      const res = await request.get("/api/login/code", {
        params: { tel },
      });
      console.log(res);
      form.setFieldValue("telCode", res.data);
    });
  };

  return (
    <div>
      <Form
        form={form}
        name="form"
        onFinish={onFinish}
        footer={
          <Button
            onClick={() => navigate("/index")}
            block
            type="submit"
            color="primary"
            size="large"
          >
            提交
          </Button>
        }
      >
        <Form.Header>水平布局表单</Form.Header>

        <Form.Item
          name="tel"
          label="手机号"
          rules={[{ required: true, message: "手机号不能为空" }]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item
          name="telCode"
          label="短信验证码"
          extra={<Button onClick={() => hanYan()}>{codeCon}</Button>}
        >
          <Input placeholder="请输入" />
        </Form.Item>
      </Form>
    </div>
  );
}

export default Index;
